const { readdir, stat, copyFile, mkdir, unlink, rmdir } = require('fs').promises
const { join } = require('path')
const sourcePath = join(__dirname, 'views/dist')
const distPath = join(__dirname, 'app/views')

async function cpf(source, dist) {
  let stats = await stat(source)
  if (stats.isFile()) {
    await copyFile(source, dist)
  } else {
    await mkdir(dist)
    await getFile(source, dist)
  }
}
async function rmf(filePath) {
  console.log(filePath)
  let stats = await stat(filePath)
  if (stats.isFile()) {
    await unlink(filePath)
  } else if (stats.isDirectory()) {
    let dirs = await readdir(filePath)
    dirs = dirs.map((dir) => rmf(join(filePath, dir)))
    await Promise.all(dirs)
    await rmdir(filePath)
  }
}
async function getFile(source, dist) {
  let files = await readdir(source)
  files = files.map((file) => {
    let newSource = join(source, file)
    let newDist = join(dist, file)
    cpf(newSource, newDist)
  })
}
const createFile = () => {
  mkdir(distPath)
    .then(() => getFile(sourcePath, distPath))
    .catch((e) => console.log(e))
}
rmf(distPath).then(createFile).catch(createFile)
